<?php

namespace app\common\controller;

use think\facade\Session;
use app\admin\model\Rule as RuleModel;
use app\admin\model\Admin as AdminModel;
use think\helper\Str;
use jsuphp\Tree;

class AddonsAdmin extends Addons
{
    public function initialize()
    {
        parent::initialize();

        if (!Session::has('admin')) {
            return $this->error('请先登录', (string)url('admin/login/index'));
        }
        $where = [
            ['id', '=', Session::get('admin.id')],
        ];
        $admin = AdminModel::with('group')->field('id,username,token,status,group_id,avatar')->where($where)->find();
        if ($admin['token'] != Session::get('admin.token')) {
            return $this->error('当前账户已再其他地方登陆,请重新登陆', (string)url('admin/index/login'));
        }
        $admin->hidden(['group_id']);
        $this->admin = $admin;
        $this->assign('admin', $admin);
        $this->menu_info();
    }

    /**
     * 检测权限
     */
    private function check_auth()
    {
        if ($this->admin['group']['rules'] != '*' && !in_array($this->menu_info['id'], explode(',', $this->admin['group']['rules']))) {
            return $this->error('暂无权限,请联系管理员');
        }
    }

    /**
     * 获取当前模块
     */
    private function menu_info()
    {
        $where = [
            'url' =>  $this->name . '://' . $this->controller . '/' . Str::snake($this->action),
        ];
        $this->menu_info = RuleModel::where($where)->find();
        if ($this->menu_info) {
            $this->check_auth();
            $this->menu_list();
            $this->assign('menu_info', $this->menu_info);
        } else {
            return $this->error('模块不存在');
        }
    }

    /**
     * 左侧菜单
     */
    private function menu_list()
    {
        if ($this->request->isAjax() || $this->request->isPost()) {
            return;
        }
        $where = [
            ['is_show', '=', 1],
            ['status', '=', 1],
        ];
        if ($this->admin['group']['rules'] != '*') {
            $where[] = ['id', 'in', $this->admin['group']['rules']];
        }

        $list = RuleModel::where($where)->cache('admin_menu_list')->order('sort desc')->select();
        $list->append(['optionss']);
        // dump($list->toArray());exit;
        $menu_list = children_menu($this->menu_info, $list->toArray());

        // dump($menu_list);exit;
        $this->assign('menu_list', $menu_list);
        //获取当前模块所有父级模块
        $menu_path = menu_path($list, $this->menu_info['pid']);
        $this->assign('menu_path', array_reverse($menu_path));
    }
}
